using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Threading.Tasks;

namespace MT5Trade.Models
{
    /// <summary>
    /// 实时监控系统 - 实现文档9.6.6节要求
    /// 提供实时交易监控、风险预警和性能指标跟踪
    /// 支持仪表板显示和自动报警机制
    /// </summary>
    public class RealTimeMonitor
    {
        #region 常量定义 - 基于文档9.6.6节

        // 监控频率（毫秒）
        public const int CRITICAL_UPDATE_INTERVAL_MS = 100;     // 关键指标更新频率
        public const int NORMAL_UPDATE_INTERVAL_MS = 1000;      // 常规指标更新频率
        public const int STATISTICS_UPDATE_INTERVAL_MS = 5000;   // 统计指标更新频率
        public const int REPORT_GENERATION_INTERVAL_MS = 60000;  // 报告生成频率

        // 预警阈值 - 基于文档9.5节风险控制矩阵
        public const double MARGIN_LEVEL_WARNING = 150;         // 保证金水平警告
        public const double MARGIN_LEVEL_CRITICAL = 100;        // 保证金水平危险
        public const double DRAWDOWN_WARNING = 0.15;           // 回撤警告阈值
        public const double DRAWDOWN_CRITICAL = 0.30;          // 回撤危险阈值
        public const int CONSECUTIVE_LOSS_WARNING = 3;          // 连续亏损警告
        public const int CONSECUTIVE_LOSS_CRITICAL = 5;         // 连续亏损危险
        public const double EXECUTION_FAILURE_RATE_WARNING = 0.05;  // 执行失败率警告
        public const double EXECUTION_FAILURE_RATE_CRITICAL = 0.10; // 执行失败率危险

        // 性能指标目标 - 基于文档9.7.1节
        public const double TARGET_SUCCESS_RATE = 0.85;         // 目标成功率
        public const double TARGET_MONTHLY_RETURN = 3000;       // 目标月收益
        public const double MAX_ACCEPTABLE_BANKRUPTCY_PROB = 0.03; // 最大可接受爆仓率

        #endregion

        #region 监控指标定义

        /// <summary>
        /// 监控指标类型
        /// </summary>
        public enum MetricType
        {
            // 实时指标
            MarginLevel,          // 保证金水平
            Equity,              // 净值
            FloatingPL,          // 浮动盈亏
            CurrentDrawdown,     // 当前回撤
            OpenPositions,       // 开仓数量
            
            // 统计指标
            SuccessRate,         // 成功率
            WinLossRatio,        // 盈亏比
            AverageProfit,       // 平均盈利
            AverageLoss,         // 平均亏损
            ConsecutiveWins,     // 连续盈利
            ConsecutiveLosses,   // 连续亏损
            
            // 风险指标
            CurrentVaR,          // 当前VaR
            CurrentCVaR,         // 当前CVaR
            BankruptcyProb,      // 破产概率
            Volatility,          // 波动率
            SharpeRatio,         // 夏普比率
            
            // 执行指标
            ExecutionSuccessRate, // 执行成功率
            AverageSlippage,     // 平均滑点
            AverageLatency,      // 平均延迟
            RetryRate            // 重试率
        }

        /// <summary>
        /// 预警级别
        /// </summary>
        public enum AlertLevel
        {
            Info,      // 信息
            Warning,   // 警告
            Critical,  // 危险
            Emergency  // 紧急
        }

        /// <summary>
        /// 监控指标数据
        /// </summary>
        public class MetricData
        {
            public MetricType Type { get; set; }
            public double Value { get; set; }
            public DateTime Timestamp { get; set; }
            public double Threshold { get; set; }
            public bool IsNormal { get; set; }
            public string Unit { get; set; }
        }

        /// <summary>
        /// 预警信息
        /// </summary>
        public class Alert
        {
            public string Id { get; set; }
            public AlertLevel Level { get; set; }
            public string Message { get; set; }
            public MetricType TriggerMetric { get; set; }
            public double TriggerValue { get; set; }
            public DateTime Timestamp { get; set; }
            public bool IsActive { get; set; }
            public string RecommendedAction { get; set; }
        }

        #endregion

        #region 私有字段

        private readonly ConcurrentDictionary<MetricType, MetricData> _currentMetrics;
        private readonly ConcurrentQueue<Alert> _activeAlerts;
        private readonly List<Alert> _alertHistory;
        private readonly Dictionary<MetricType, List<double>> _metricHistory;
        private readonly Timer _criticalTimer;
        private readonly Timer _normalTimer;
        private readonly Timer _statisticsTimer;
        private readonly Timer _reportTimer;
        private readonly object _lockObj = new object();
        
        private DateTime _startTime;
        private int _totalTrades;
        private int _successfulTrades;
        private int _failedTrades;
        private double _totalProfit;
        private double _totalLoss;
        private double _peakEquity;
        private double _currentEquity;
        private int _consecutiveWins;
        private int _consecutiveLosses;
        private bool _isMonitoring;

        // 事件
        public event EventHandler<Alert> OnAlertTriggered;
        public event EventHandler<Dictionary<MetricType, MetricData>> OnMetricsUpdated;
        public event EventHandler<MonitoringReport> OnReportGenerated;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化实时监控系统
        /// </summary>
        public RealTimeMonitor()
        {
            _currentMetrics = new ConcurrentDictionary<MetricType, MetricData>();
            _activeAlerts = new ConcurrentQueue<Alert>();
            _alertHistory = new List<Alert>();
            _metricHistory = new Dictionary<MetricType, List<double>>();
            
            // 初始化所有指标历史
            foreach (MetricType metric in Enum.GetValues(typeof(MetricType)))
            {
                _metricHistory[metric] = new List<double>();
                _currentMetrics[metric] = new MetricData
                {
                    Type = metric,
                    Value = 0,
                    Timestamp = DateTime.Now,
                    IsNormal = true
                };
            }
            
            // 初始化定时器
            _criticalTimer = new Timer(CRITICAL_UPDATE_INTERVAL_MS);
            _criticalTimer.Elapsed += UpdateCriticalMetrics;
            
            _normalTimer = new Timer(NORMAL_UPDATE_INTERVAL_MS);
            _normalTimer.Elapsed += UpdateNormalMetrics;
            
            _statisticsTimer = new Timer(STATISTICS_UPDATE_INTERVAL_MS);
            _statisticsTimer.Elapsed += UpdateStatistics;
            
            _reportTimer = new Timer(REPORT_GENERATION_INTERVAL_MS);
            _reportTimer.Elapsed += GenerateReport;
            
            _startTime = DateTime.Now;
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 启动监控
        /// </summary>
        public void StartMonitoring()
        {
            lock (_lockObj)
            {
                if (!_isMonitoring)
                {
                    _isMonitoring = true;
                    _startTime = DateTime.Now;
                    
                    _criticalTimer.Start();
                    _normalTimer.Start();
                    _statisticsTimer.Start();
                    _reportTimer.Start();
                }
            }
        }

        /// <summary>
        /// 停止监控
        /// </summary>
        public void StopMonitoring()
        {
            lock (_lockObj)
            {
                if (_isMonitoring)
                {
                    _isMonitoring = false;
                    
                    _criticalTimer.Stop();
                    _normalTimer.Stop();
                    _statisticsTimer.Stop();
                    _reportTimer.Stop();
                }
            }
        }

        /// <summary>
        /// 更新交易结果
        /// </summary>
        public void UpdateTradeResult(bool isSuccess, double profit, double slippage, double latency)
        {
            lock (_lockObj)
            {
                _totalTrades++;
                
                if (isSuccess)
                {
                    _successfulTrades++;
                    _consecutiveWins++;
                    _consecutiveLosses = 0;
                    
                    if (profit > 0)
                    {
                        _totalProfit += profit;
                    }
                    else
                    {
                        _totalLoss += Math.Abs(profit);
                    }
                }
                else
                {
                    _failedTrades++;
                    _consecutiveLosses++;
                    _consecutiveWins = 0;
                }
                
                // 更新执行指标
                UpdateMetric(MetricType.ExecutionSuccessRate, 
                    _totalTrades > 0 ? (double)_successfulTrades / _totalTrades : 0);
                UpdateMetric(MetricType.AverageSlippage, slippage);
                UpdateMetric(MetricType.AverageLatency, latency);
                
                // 检查连续亏损
                CheckConsecutiveLosses();
            }
        }

        /// <summary>
        /// 更新账户状态
        /// </summary>
        public void UpdateAccountStatus(
            double equity,
            double marginLevel,
            double floatingPL,
            int openPositions)
        {
            lock (_lockObj)
            {
                _currentEquity = equity;
                
                // 更新峰值
                if (equity > _peakEquity)
                {
                    _peakEquity = equity;
                }
                
                // 计算回撤
                double drawdown = _peakEquity > 0 ? 
                    (_peakEquity - equity) / _peakEquity : 0;
                
                // 更新指标
                UpdateMetric(MetricType.Equity, equity);
                UpdateMetric(MetricType.MarginLevel, marginLevel);
                UpdateMetric(MetricType.FloatingPL, floatingPL);
                UpdateMetric(MetricType.CurrentDrawdown, drawdown);
                UpdateMetric(MetricType.OpenPositions, openPositions);
                
                // 检查保证金水平
                CheckMarginLevel(marginLevel);
                
                // 检查回撤
                CheckDrawdown(drawdown);
            }
        }

        /// <summary>
        /// 更新风险指标
        /// </summary>
        public void UpdateRiskMetrics(
            double currentVaR,
            double currentCVaR,
            double bankruptcyProb,
            double volatility,
            double sharpeRatio)
        {
            lock (_lockObj)
            {
                UpdateMetric(MetricType.CurrentVaR, currentVaR);
                UpdateMetric(MetricType.CurrentCVaR, currentCVaR);
                UpdateMetric(MetricType.BankruptcyProb, bankruptcyProb);
                UpdateMetric(MetricType.Volatility, volatility);
                UpdateMetric(MetricType.SharpeRatio, sharpeRatio);
                
                // 检查破产概率
                if (bankruptcyProb > MAX_ACCEPTABLE_BANKRUPTCY_PROB)
                {
                    TriggerAlert(AlertLevel.Critical,
                        $"破产概率({bankruptcyProb:P2})超过安全阈值({MAX_ACCEPTABLE_BANKRUPTCY_PROB:P2})",
                        MetricType.BankruptcyProb,
                        bankruptcyProb,
                        "立即降低杠杆和仓位大小");
                }
            }
        }

        /// <summary>
        /// 获取当前所有指标
        /// </summary>
        public Dictionary<MetricType, MetricData> GetCurrentMetrics()
        {
            return new Dictionary<MetricType, MetricData>(_currentMetrics);
        }

        /// <summary>
        /// 获取活动预警
        /// </summary>
        public List<Alert> GetActiveAlerts()
        {
            return _activeAlerts.Where(a => a.IsActive).ToList();
        }

        /// <summary>
        /// 获取仪表板数据
        /// </summary>
        public DashboardData GetDashboardData()
        {
            lock (_lockObj)
            {
                return new DashboardData
                {
                    // 核心指标
                    CurrentEquity = _currentEquity,
                    TotalProfit = _totalProfit - _totalLoss,
                    SuccessRate = _totalTrades > 0 ? 
                        (double)_successfulTrades / _totalTrades : 0,
                    CurrentDrawdown = _currentMetrics[MetricType.CurrentDrawdown].Value,
                    
                    // 风险指标
                    MarginLevel = _currentMetrics[MetricType.MarginLevel].Value,
                    CurrentVaR = _currentMetrics[MetricType.CurrentVaR].Value,
                    BankruptcyProbability = _currentMetrics[MetricType.BankruptcyProb].Value,
                    
                    // 交易统计
                    TotalTrades = _totalTrades,
                    WinningTrades = _successfulTrades,
                    LosingTrades = _totalTrades - _successfulTrades,
                    ConsecutiveWins = _consecutiveWins,
                    ConsecutiveLosses = _consecutiveLosses,
                    
                    // 预警信息
                    ActiveAlerts = GetActiveAlerts(),
                    AlertCounts = new Dictionary<AlertLevel, int>
                    {
                        { AlertLevel.Info, _activeAlerts.Count(a => a.Level == AlertLevel.Info) },
                        { AlertLevel.Warning, _activeAlerts.Count(a => a.Level == AlertLevel.Warning) },
                        { AlertLevel.Critical, _activeAlerts.Count(a => a.Level == AlertLevel.Critical) },
                        { AlertLevel.Emergency, _activeAlerts.Count(a => a.Level == AlertLevel.Emergency) }
                    },
                    
                    // 时间信息
                    MonitoringDuration = DateTime.Now - _startTime,
                    LastUpdateTime = DateTime.Now
                };
            }
        }

        /// <summary>
        /// 生成监控报告
        /// </summary>
        public MonitoringReport GenerateMonitoringReport()
        {
            lock (_lockObj)
            {
                var report = new MonitoringReport
                {
                    ReportId = Guid.NewGuid().ToString(),
                    GeneratedAt = DateTime.Now,
                    Period = new TimeSpan(DateTime.Now.Ticks - _startTime.Ticks),
                    
                    // 性能指标
                    PerformanceMetrics = new PerformanceMetrics
                    {
                        TotalReturn = _totalProfit - _totalLoss,
                        ReturnRate = _peakEquity > 0 ? 
                            (_currentEquity - _peakEquity) / _peakEquity : 0,
                        SuccessRate = _totalTrades > 0 ? 
                            (double)_successfulTrades / _totalTrades : 0,
                        WinLossRatio = _totalLoss > 0 ? 
                            _totalProfit / _totalLoss : double.MaxValue,
                        MaxDrawdown = _metricHistory[MetricType.CurrentDrawdown].Max(),
                        SharpeRatio = _currentMetrics[MetricType.SharpeRatio].Value
                    },
                    
                    // 风险指标
                    RiskMetrics = new RiskMetricsSummary
                    {
                        AverageVaR = _metricHistory[MetricType.CurrentVaR].Average(),
                        MaxVaR = _metricHistory[MetricType.CurrentVaR].Max(),
                        AverageCVaR = _metricHistory[MetricType.CurrentCVaR].Average(),
                        MaxBankruptcyProb = _metricHistory[MetricType.BankruptcyProb].Max(),
                        AverageVolatility = _metricHistory[MetricType.Volatility].Average()
                    },
                    
                    // 预警汇总
                    AlertSummary = new AlertSummary
                    {
                        TotalAlerts = _alertHistory.Count,
                        CriticalAlerts = _alertHistory.Count(a => a.Level == AlertLevel.Critical),
                        WarningAlerts = _alertHistory.Count(a => a.Level == AlertLevel.Warning),
                        MostFrequentAlert = _alertHistory
                            .GroupBy(a => a.TriggerMetric)
                            .OrderByDescending(g => g.Count())
                            .FirstOrDefault()?.Key.ToString()
                    },
                    
                    // 建议
                    Recommendations = GenerateRecommendations()
                };
                
                OnReportGenerated?.Invoke(this, report);
                return report;
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 更新关键指标
        /// </summary>
        private void UpdateCriticalMetrics(object sender, ElapsedEventArgs e)
        {
            // 这里应该从实际交易系统获取数据
            // 目前作为示例
            OnMetricsUpdated?.Invoke(this, GetCurrentMetrics());
        }

        /// <summary>
        /// 更新常规指标
        /// </summary>
        private void UpdateNormalMetrics(object sender, ElapsedEventArgs e)
        {
            // 更新成功率等统计指标
            if (_totalTrades > 0)
            {
                UpdateMetric(MetricType.SuccessRate, (double)_successfulTrades / _totalTrades);
                UpdateMetric(MetricType.WinLossRatio, 
                    _totalLoss > 0 ? _totalProfit / _totalLoss : 0);
            }
        }

        /// <summary>
        /// 更新统计信息
        /// </summary>
        private void UpdateStatistics(object sender, ElapsedEventArgs e)
        {
            // 计算平均值
            if (_successfulTrades > 0)
            {
                UpdateMetric(MetricType.AverageProfit, _totalProfit / _successfulTrades);
            }
            
            if (_failedTrades > 0)
            {
                UpdateMetric(MetricType.AverageLoss, _totalLoss / _failedTrades);
            }
        }

        /// <summary>
        /// 生成报告
        /// </summary>
        private void GenerateReport(object sender, ElapsedEventArgs e)
        {
            //GenerateMonitoringReport();
        }

        /// <summary>
        /// 更新指标
        /// </summary>
        private void UpdateMetric(MetricType type, double value)
        {
            var metric = new MetricData
            {
                Type = type,
                Value = value,
                Timestamp = DateTime.Now,
                IsNormal = true
            };
            
            _currentMetrics[type] = metric;
            
            // 记录历史
            if (_metricHistory[type].Count > 10000)
            {
                _metricHistory[type].RemoveAt(0);
            }
            _metricHistory[type].Add(value);
        }

        /// <summary>
        /// 触发预警
        /// </summary>
        private void TriggerAlert(
            AlertLevel level,
            string message,
            MetricType triggerMetric,
            double triggerValue,
            string recommendedAction)
        {
            var alert = new Alert
            {
                Id = Guid.NewGuid().ToString(),
                Level = level,
                Message = message,
                TriggerMetric = triggerMetric,
                TriggerValue = triggerValue,
                Timestamp = DateTime.Now,
                IsActive = true,
                RecommendedAction = recommendedAction
            };
            
            _activeAlerts.Enqueue(alert);
            _alertHistory.Add(alert);
            
            // 保持队列大小
            while (_activeAlerts.Count > 100)
            {
                _activeAlerts.TryDequeue(out _);
            }
            
            OnAlertTriggered?.Invoke(this, alert);
        }

        /// <summary>
        /// 检查保证金水平
        /// </summary>
        private void CheckMarginLevel(double marginLevel)
        {
            if (marginLevel < MARGIN_LEVEL_CRITICAL)
            {
                TriggerAlert(AlertLevel.Emergency,
                    $"保证金水平危险: {marginLevel:F2}% < {MARGIN_LEVEL_CRITICAL}%",
                    MetricType.MarginLevel,
                    marginLevel,
                    "立即平仓部分头寸或追加保证金");
            }
            else if (marginLevel < MARGIN_LEVEL_WARNING)
            {
                TriggerAlert(AlertLevel.Warning,
                    $"保证金水平警告: {marginLevel:F2}% < {MARGIN_LEVEL_WARNING}%",
                    MetricType.MarginLevel,
                    marginLevel,
                    "准备降低仓位或追加资金");
            }
        }

        /// <summary>
        /// 检查回撤
        /// </summary>
        private void CheckDrawdown(double drawdown)
        {
            if (drawdown > DRAWDOWN_CRITICAL)
            {
                TriggerAlert(AlertLevel.Critical,
                    $"回撤过大: {drawdown:P2} > {DRAWDOWN_CRITICAL:P2}",
                    MetricType.CurrentDrawdown,
                    drawdown,
                    "暂停交易，重新评估策略");
            }
            else if (drawdown > DRAWDOWN_WARNING)
            {
                TriggerAlert(AlertLevel.Warning,
                    $"回撤警告: {drawdown:P2} > {DRAWDOWN_WARNING:P2}",
                    MetricType.CurrentDrawdown,
                    drawdown,
                    "降低仓位和风险敷口");
            }
        }

        /// <summary>
        /// 检查连续亏损
        /// </summary>
        private void CheckConsecutiveLosses()
        {
            if (_consecutiveLosses >= CONSECUTIVE_LOSS_CRITICAL)
            {
                TriggerAlert(AlertLevel.Critical,
                    $"连续亏损过多: {_consecutiveLosses} 次",
                    MetricType.ConsecutiveLosses,
                    _consecutiveLosses,
                    "立即暂停交易，分析失败原因");
            }
            else if (_consecutiveLosses >= CONSECUTIVE_LOSS_WARNING)
            {
                TriggerAlert(AlertLevel.Warning,
                    $"连续亏损警告: {_consecutiveLosses} 次",
                    MetricType.ConsecutiveLosses,
                    _consecutiveLosses,
                    "检查交易策略和市场条件");
            }
        }

        /// <summary>
        /// 生成建议
        /// </summary>
        private List<string> GenerateRecommendations()
        {
            var recommendations = new List<string>();
            
            // 基于成功率
            var successRate = _totalTrades > 0 ? (double)_successfulTrades / _totalTrades : 0;
            if (successRate < TARGET_SUCCESS_RATE)
            {
                recommendations.Add($"成功率({successRate:P1})低于目标({TARGET_SUCCESS_RATE:P0})，建议优化入场时机选择");
            }
            
            // 基于回撤
            var maxDrawdown = _metricHistory[MetricType.CurrentDrawdown].Any() ? 
                _metricHistory[MetricType.CurrentDrawdown].Max() : 0;
            if (maxDrawdown > 0.2)
            {
                recommendations.Add($"最大回撤({maxDrawdown:P1})过高，建议加强风险控制");
            }
            
            // 基于连续亏损
            if (_consecutiveLosses > 2)
            {
                recommendations.Add("出现连续亏损，建议检查市场状态和策略有效性");
            }
            
            return recommendations;
        }

        #endregion

        #region 辅助类

        /// <summary>
        /// 仪表板数据
        /// </summary>
        public class DashboardData
        {
            public double CurrentEquity { get; set; }
            public double TotalProfit { get; set; }
            public double SuccessRate { get; set; }
            public double CurrentDrawdown { get; set; }
            public double MarginLevel { get; set; }
            public double CurrentVaR { get; set; }
            public double BankruptcyProbability { get; set; }
            public int TotalTrades { get; set; }
            public int WinningTrades { get; set; }
            public int LosingTrades { get; set; }
            public int ConsecutiveWins { get; set; }
            public int ConsecutiveLosses { get; set; }
            public List<Alert> ActiveAlerts { get; set; }
            public Dictionary<AlertLevel, int> AlertCounts { get; set; }
            public TimeSpan MonitoringDuration { get; set; }
            public DateTime LastUpdateTime { get; set; }
        }

        /// <summary>
        /// 监控报告
        /// </summary>
        public class MonitoringReport
        {
            public string ReportId { get; set; }
            public DateTime GeneratedAt { get; set; }
            public TimeSpan Period { get; set; }
            public PerformanceMetrics PerformanceMetrics { get; set; }
            public RiskMetricsSummary RiskMetrics { get; set; }
            public AlertSummary AlertSummary { get; set; }
            public List<string> Recommendations { get; set; }
        }

        /// <summary>
        /// 性能指标
        /// </summary>
        public class PerformanceMetrics
        {
            public double TotalReturn { get; set; }
            public double ReturnRate { get; set; }
            public double SuccessRate { get; set; }
            public double WinLossRatio { get; set; }
            public double MaxDrawdown { get; set; }
            public double SharpeRatio { get; set; }
        }

        /// <summary>
        /// 风险指标汇总
        /// </summary>
        public class RiskMetricsSummary
        {
            public double AverageVaR { get; set; }
            public double MaxVaR { get; set; }
            public double AverageCVaR { get; set; }
            public double MaxBankruptcyProb { get; set; }
            public double AverageVolatility { get; set; }
        }

        /// <summary>
        /// 预警汇总
        /// </summary>
        public class AlertSummary
        {
            public int TotalAlerts { get; set; }
            public int CriticalAlerts { get; set; }
            public int WarningAlerts { get; set; }
            public string MostFrequentAlert { get; set; }
        }

        #endregion
    }
}